package com.fruit.controller.wap.lightpay;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alipay.api.AlipayApiException;
import com.fruit.alipay.util.AlipayUtil;
import com.fruit.constants.PayConstant;
import com.fruit.controller.base.BaseController;
import com.fruit.pojo.lightpay.LightPayCashierAlipay;
import com.fruit.pojo.sys.AlipayConfig;
import com.fruit.pojo.sys.WechatConfig;
import com.fruit.service.lightpay.LightPayNotifyManager;
import com.fruit.service.sys.SysManager;
import com.fruit.util.CommonUtil;
import com.fruit.util.RequestHandler;
import com.fruit.util.ResultInfo;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping(value = "/wap/notify/")
public class LightPayNotifyController extends BaseController {

	
	@Autowired
	private LightPayNotifyManager lightPayNotifyService;
	
	@Autowired
	private SysManager sysService;

	@RequestMapping(value="aliPayNotify")
	public void agentAliPayNotify(HttpServletRequest request,
			HttpServletResponse response){
		String tradeId = CommonUtil.getUUID();
		log.info("[{}]-【支付宝回调】-【开始】",tradeId);
		Map<String, String> map = new HashMap<String, String>();
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e1) {
			log.error("[{}]-【支付宝回调】-【异常】",tradeId);
			e1.printStackTrace();
		}
		
		try {
			Map<String, String[]> params = request.getParameterMap();
			for (Entry<String, String[]> entry : params.entrySet()) {
				if (entry.getValue() != null && entry.getValue().length == 1) {
					map.put(entry.getKey(), entry.getValue()[0]);
				}
			}
			log.info("[{}]-【支付宝回调】-【验证参数】",tradeId);
			AlipayConfig ac = sysService.getAlipayConfig();
			LightPayCashierAlipay result = AlipayUtil.getNotifyResult(map,ac);
			log.info("[{}]-【支付宝回调】-【调用收银服务】",tradeId);
			Map<String,Object> resMap = lightPayNotifyService.updateLightPayCashier(tradeId, result);
			ResultInfo ri = (ResultInfo)resMap.get("result");
			if(ResultInfo.SUCCESS.equals(ri.getState())){
				log.info("[{}]-【支付宝回调】-【成功】",tradeId);
				out.write("success");
			}else{
				log.error("[{}]-【支付宝回调】-【异常】-【返回：fail】",tradeId);
				out.write("fail");
			}
			

		} catch (AlipayApiException e) {
			log.error("[{}]-【支付宝回调】-【异常】-【返回：fail】",tradeId);
			out.write("fail");
		}
		log.info("[{}]-【支付宝回调】-【结束】",tradeId);

	}	
	
	@RequestMapping(value="wechatNotify")
	public void wechatNotify(HttpServletRequest request,
			HttpServletResponse response){
		String tradeId = CommonUtil.getUUID();
		log.info("[{}]-【微信支付回调】-【开始】",tradeId);
		
		try{
			InputStream inputStream;
			StringBuffer sb = new StringBuffer();
			inputStream = request.getInputStream();
			String s;
			
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));  
	        while ((s = in.readLine()) != null){  
	            sb.append(s);  
	        }  
	        in.close();  
	        inputStream.close();  
			
	        Map<String, String> resParams = CommonUtil.xmlBody2map(sb.toString(), "xml");
	        String resXml = "";
	        if(resParams == null || resParams.isEmpty()){
	        	log.error("[{}]-【微信支付回调】-【异常】-【返回：FAIL】",tradeId);
	        	resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";
	        }else{
	        	if(PayConstant.CODE_SUCCESS.equals(resParams.get("return_code"))){
	        		String sign = resParams.get("sign");
	        		RequestHandler reqH = new RequestHandler();
	        		WechatConfig wc = sysService.getWechatConfig();
	        		reqH.setKey(wc.getApiKey());
	        		String mySign = reqH.createSign(resParams);
	        		if(StringUtils.isNotEmpty(mySign) && StringUtils.equals(mySign, sign)){
	        			lightPayNotifyService.updateLightPayCashierByWechat(tradeId, resParams, sb.toString());
	        			log.info("[{}]-【微信支付回调】-【成功】",tradeId);
	        			resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
	        		}else{
	        			log.error("[{}]-【微信支付回调】-【异常】-【返回：FAIL】",tradeId);
	        			resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[参数错误]]></return_msg></xml>";
	        		}
	        		
	        	}else{
	        		log.error("[{}]-【微信支付回调】-【异常】-【返回：FAIL】",tradeId);
	        		resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";
	        	}
	        }
	        BufferedOutputStream out = new BufferedOutputStream(  
	                response.getOutputStream());  
	        out.write(resXml.getBytes());  
	        out.flush();  
	        out.close();  
	        
			}catch(Exception e){
				log.error("[{}]-【微信支付回调】-【异常】-【返回：FAIL】",tradeId);
				e.printStackTrace();
				
			}
		log.info("[{}]-【微信支付回调】-【结束】",tradeId);
	}
	
}
